<template>
  <div
    v-if="props.tabTop"
    style="width: 100%; background-color: white; border-radius: 10px 10px 0 0"
    class="pad10"
    :class="{ 'box-shadow': props.theme == 'light' }"
  >
    <div class="flex jbetween acenter">
      <div style="width: 100%">
        <slot name="tabTop"></slot>
      </div>
      <div class="flex acenters">
        <pagination
          class="mgr10"
          v-if="props.showPage"
          v-show="props.total > 0"
          :total="props.total"
          v-model:page="props.page.PageIndex"
          v-model:limit="props.page.PageSize"
          @pagination="getList"
        /><right-toolbar
          v-if="props.toolbar"
          v-model:showSearch="showSearch"
          v-model:searchStatus="mySearchStatus"
          @queryTable="getList"
          :columns="totalCol"
        ></right-toolbar>
      </div>
    </div>
    <div>
      <slot name="secondRow"></slot>
    </div>
  </div>

  <el-table
    class="slide-in-elliptic-top-fwd"
    :data="props.tableList"
    :border="props.border"
    @selection-change="handleSelectionChange"
    row-key="ID"
    :stripe="props.stripe"
    ref="tabRef"
    :max-height="props.height"
    @row-click="handleRowClick"
    :header-row-class-name="
      props.theme == 'light' ? 'TableHeaderClass' : 'TableHeaderDarkClass'
    "
    :row-class-name="
      props.theme == 'light' ? 'TableRowClass' : 'TableRowDarkClass'
    "
    :class="props.tabTop ? '' : 'notTabTop'"
  >
    <el-table-column
      v-for="(item, index) in myColumns"
      :reserve-selection="props.selection"
      :key="item.key"
      :label="item.label == '多选框' ? '' : item.label"
      :width="filterTableWidth(item)"
      :type="filterTableType(item.label)"
      :prop="item.prop"
      :show-overflow-tooltip="item.hideTooltip ? false : props.tooltip"
      :align="'center'"
      :fixed="item.label == '操作' ? 'right' : false"
    >
      <!-- 单选框 -->
      <template v-if="item.label == '单选框'" v-slot="{ row, $index }">
        <div @click="handleRadioCheck(row, item)" class="flex acenter jcenter">
          <div
            v-if="radioBox == row[item.prop ? item.prop : 'ID']"
            style="height: 24px; width: 24px"
          >
            <el-icon :size="26" color="#67C23A"><CircleCheckFilled /></el-icon>
          </div>
          <div v-else class="circle"></div>
        </div>
      </template>
      <!-- 序号 -->
      <template v-if="item.label == '序号'" v-slot="{ row, $index }">
        {{
          $index +
          1 +
          Number(props.page.PageIndex - 1) * Number(props.page.PageSize)
        }}
      </template>
      <!-- 多数据 -->
      <template v-if="item.tooltip" v-slot="{ row }">
        <el-tooltip placement="top">
          <template #content>
            <div v-for="tip in row[item.prop]">
              {{ tip }}
            </div>
          </template>
          <div class="overShow">{{ $arrTurnStr(row[item.prop], 'item') }}</div>
        </el-tooltip>
      </template>
      <!-- 链接 -->
      <template v-if="item.link" v-slot="{ row }">
        <el-link type="primary" @click="linkHandle(row)">{{
          row[item.prop]
        }}</el-link>
      </template>
      <!-- 文件 -->
      <template v-if="item.file" v-slot="{ row }">
        <el-link type="primary" @click="downloadFile(row)">{{
          row[item.prop]
        }}</el-link>
      </template>
      <!-- 用户 -->
      <template v-if="item.user" v-slot="{ row }">
        {{ filterUserName(row[item.prop]) }}
      </template>
      <!-- 类型 -->
      <template v-if="item.types" v-slot="{ row }">
        {{ item.types[row[item.prop]] }}
      </template>
      <!-- 输入框 -->
      <template v-if="item.input" v-slot="{ row }">
        <el-input v-model="row[item.prop]" placeholder="请输入" />
      </template>
      <!-- 数字输入框 -->
      <template v-if="item.inputNum" v-slot="{ row }">
        <el-input-number
          v-model="row[item.prop]"
          placeholder="请输入"
          v-number
          controls-position="right"
        />
      </template>
      <!-- 时间输入框 -->
      <template v-if="item.time" v-slot="{ row }">
        <MyDateTime width="200px" v-model="row[item.prop]" />
      </template>
      <!-- 选择框 -->
      <template v-if="item.select" v-slot="{ row }">
        <Selector
          v-model="row[item.prop]"
          :category="item.category"
          :query="item.query"
          :clearable="false"
        />
      </template>
      <!-- 评分 -->
      <template v-if="item.rate" v-slot="{ row }">
        <el-rate
          v-model="row[item.prop]"
          allow-half
          :disabled="item.disabled"
        />
      </template>
      <!-- 标签 -->
      <template v-if="item.tag" v-slot="{ row }">
        <div v-for="(tag, tindex) in row[item.prop]">
          <el-tag
            v-if="tag.name"
            :key="tindex"
            :type="tag.type"
            :color="tag.color"
            effect="dark"
            round
            :size="tag.size"
            >{{ tag.name }}</el-tag
          >
        </div>
      </template>
      <!-- 图片 -->
      <template v-if="item.img" v-slot="{ row }">
        <el-image
          style="width: 30px; height: 30px"
          :src="$addFileHead(row[item.prop])"
          preview-teleported
          :preview-src-list="[$addFileHead(row[item.prop])]"
          fit="fill"
        />
      </template>
      <!-- 颜色 -->
      <template v-if="item.color" v-slot="{ row }">
        <div :style="'color:' + row[item.prop + 'color']">
          {{ row[item.prop] }}
        </div>
      </template>
      <!-- 开关 -->
      <template v-if="item.switch" v-slot="{ row }">
        <el-switch
          :active-value="item.active"
          :inactive-value="item.inactive"
          v-model="row[item.prop]"
          @change="switchChange(row, $event)"
        />
      </template>

      <!-- 操作 -->
      <template v-if="item.label == '操作'" v-slot="{ row }">
        <el-dropdown
          trigger="click"
          v-if="HasOperation(row)"
          @command="handleDropdown($event, row)"
        >
          <el-icon class="pointer" :size="20" style="transform: rotateZ(90deg)"
            ><MoreFilled
          /></el-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-if="props.btnList.includes('check')"
                :command="{ name: '查看' }"
              >
                <el-button type="text" style="color: #606266; height: 22px"
                  ><el-icon><View /></el-icon>查看</el-button
                ></el-dropdown-item
              >
              <el-dropdown-item
                :command="{ name: '编辑' }"
                v-if="props.btnList.includes('edit')"
              >
                <el-icon><Edit /></el-icon>编辑
              </el-dropdown-item>

              <!-- 自定义 -->
              <div
                v-if="props.customBtn && props.customBtn.length"
                v-for="btn in props.customBtn"
              >
                <el-dropdown-item
                  :command="{ name: '自定义', row, btnName: btn.name }"
                  v-if="!btn.rule"
                >
                  <el-icon><Link /></el-icon>{{ btn.name }}
                </el-dropdown-item>
                <el-dropdown-item
                  :command="{ name: '自定义', row, btnName: btn.name }"
                  v-if="btn.rule && row[btn.rule.key] == btn.rule.status"
                >
                  <el-button
                    type="text"
                    :style="'height: 22px;color:' + btn.color"
                  >
                    <el-icon><Link /></el-icon>{{ btn.name }}</el-button
                  >
                </el-dropdown-item>
              </div>

              <el-dropdown-item
                v-if="props.btnList.includes('delete')"
                :command="{ name: '删除' }"
              >
                <el-popover trigger="hover" placement="left" :width="230">
                  <template #reference>
                    <el-button type="text" style="color: red; height: 22px">
                      <el-icon><Delete /></el-icon>删除</el-button
                    >
                  </template>
                  <div class="flex acenter">
                    <div style="margin-bottom: -2px !important">
                      <el-icon color="#E6A23C"><QuestionFilled /></el-icon>
                    </div>
                    <div>
                      确认删除该数据吗?<el-button
                        type=""
                        style="margin-left: 20px"
                        plain
                        size="small"
                        @click="oprationHandle(row, 'delete')"
                        >确认</el-button
                      >
                    </div>
                  </div>
                </el-popover>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </el-table-column>
    <ActiveCol
      :customColList="props.customColList"
      :activeCol="props.activeCol"
      :totalCol="totalCol"
    />
  </el-table>
</template>

<script setup name="MyTable">
import { getCurrentInstance, nextTick, onMounted, watch } from 'vue';
import useUserStore from '@/store/modules/user.js';
import { saveAs } from 'file-saver';
import { ElMessageBox } from 'element-plus';
const { proxy } = getCurrentInstance();
const emit = defineEmits([
  'update:selectList',
  'getList',
  'edit',
  'check',
  'delete',
  'link',
  'update:searchStatus',
  'update:page',
  'switch',
  'beforSwitch',
  'radio',
  'select',
  'custom'
]);
const props = defineProps({
  tableList: {
    default: []
  },
  tabTop: {
    default: true
  },
  border: {
    default: false
  },
  columns: {
    default: []
  },
  tooltip: {
    default: true
  },
  selection: {
    default: true
  },
  page: {
    default: {
      PageIndex: 1,
      PageSize: 10
    }
  },
  total: {
    default: 0
  },
  showPage: {
    default: true
  },
  btnList: {
    default: ['edit', 'delete', 'check']
  },
  customColList: {
    default: []
  },
  activeCol: {
    default: []
  },
  showSearch: {
    default: true
  },
  searchStatus: {
    default: true
  },
  stripe: {
    default: false
  },
  selectList: {
    default: []
  },
  toolbar: {
    default: true
  },
  tabRef: {
    default: {}
  },
  height: {},
  customBtn: {
    default: []
  },
  activeRadio: {
    default: ''
  },
  theme: {
    default: 'light'
  }
});
const radioBox = ref('');
const totalCol = ref([]);
const look = ref(false);
const confrimDelete = ref(false);
watch(
  () => props.activeCol,
  (n, o) => {
    totalCol.value = [...props.columns, ...props.activeCol];
  },
  {
    deep: true,
    immediate: true
  }
);
watch(
  () => props.columns,
  (n, o) => {
    totalCol.value = [...props.columns, ...props.activeCol];
  },
  {
    immediate: true
  }
);
watch(
  () => props.tableList,
  n => {
    if (!look.value) {
      originSelect.value = props.selectList;
    }
    look.value = true;
    if (props.activeRadio) {
      radioBox.value = props.activeRadio;
    }
    props.tableList?.map(item => {
      props.selectList?.map(item2 => {
        if (item.ID == item2.ID) {
          item.Remark = item2.Remark;
          let ids = selectRows.value?.map(s => s.ID);
          if (!ids.includes(item2.ID)) {
            tabRef.value.toggleRowSelection(item, true);
          }
        }
      });
    });
  },
  {
    deep: true
    // immediate: true,
  }
);

const selectRows = ref([]);
const originSelect = ref([]);
const tabRef = ref();
const myColumns = computed({
  get: () => {
    let list = props.columns?.filter(item => item.visible);
    if (!props.btnList?.length && !props.customBtn?.length) {
      list = list?.filter(item => item.label != '操作');
    }
    return list;
  }
});

const mySearchStatus = computed({
  get: () => props.searchStatus,
  set: n => {
    emit('update:searchStatus', n);
  }
});

onMounted(() => {
  nextTick(() => {
    tabRef.value?.clearSelection();
  });
  originSelect.value = props.selectList;
});

function handleDropdown(command, row) {
  switch (command.name) {
    case '查看':
      console.log(row);
      oprationHandle(row, 'check');
      break;
    case '编辑':
      oprationHandle(row, 'edit');
      break;
    case '删除':
      // oprationHandle(row, 'delete');
      break;
    case '自定义':
      row.btnName = command.btnName;
      emit('custom', row);
      break;
  }
}

function HasOperation(row) {
  let bool =
    props.btnList?.includes('check') ||
    props.btnList?.includes('edit') ||
    props.btnList?.includes('delete');
  let bool2 = false;
  bool2 = props.customBtn?.some(item => {
    if (item.rule) {
      return item.rule.status == row[item.rule.key];
    } else {
      return true;
    }
  });
  return bool || bool2;
}

function downloadFile(row) {
  saveAs(proxy.$addFileHead(row.Path));
}

function handleRowClick(row) {
  let item = myColumns.value?.find(item => item.label == '单选框');
  if (item) {
    radioBox.value = row[item.prop ? item.prop : 'ID'];
    emit('radio', row);
  }
}

const handleSelectionChange = rows => {
  selectRows.value = rows;
  originSelect.value = originSelect.value?.filter(item => {
    let bool = rows?.some(item2 => item.ID == item2.ID);
    return !bool;
  });
  let list = [...originSelect.value, ...rows];
  emit('update:selectList', list);
  emit('select', rows);
};

function handleRadioCheck(row, item) {
  // radioBox.value = row[item.prop ? item.prop : 'ID'];
  // emit('radio', row);
}

function filterUserName(id) {
  if (!id) return;
  let item = useUserStore().allUserList?.find(item => item.ID == id);
  return item?.Name;
}

const filterTableWidth = item => {
  switch (item.label) {
    case '序号':
      return '60';
    case '多选框':
      return '60';
    case '操作':
      return '60';
    default:
      return item.width ? item.width : '';
  }
};

const filterTableType = label => {
  switch (label) {
    case '序号':
      return 'index';
    case '多选框':
      return 'selection';
    default:
      '';
  }
};

const oprationHandle = (row, type) => {
  switch (type) {
    case 'check':
      emit('check', row);
      break;
    case 'edit':
      emit('edit', row);
      break;
    case 'delete':
      emit('delete', row);
      confrimDelete.value = false;
      break;
  }
};

function switchChange(row, status) {
  emit('switch', { row, status });
}

const linkHandle = row => {
  emit('link', row);
};
const getList = val => {
  if (val) {
    look.value = false;
    emit('update:page', { PageIndex: val.page, PageSize: val.limit });
  }
  emit('getList');
};
defineExpose({
  tabRef
});
</script>

<style lang="scss" scoped>
.circle {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  border: 1px solid rgb(172, 172, 172);
}
:deep(.el-popper) {
  .el-popover__title {
    font-size: 12px !important;
  }
}
</style>
